# -*- coding: utf-8 -*-
# @Time : 2022/2/16 18:37

from src.Case.Database.case_name_database import CaseName, CaseNameSchema
from Common.yaml_method import YamlMethod


def sort_children(node):
    """
    递归排序 children
    :param node:
    :return:
    """
    node['children'].sort(key=lambda x: x['case_name'])
    for child in node['children']:
        sort_children(child)


class CaseNameTree:
    """
    获取用例名称,并转换成树形结构
    """

    @staticmethod
    def case_name_tree():
        """
        获取用例名称,并转换成树形结构口
        :return:
        """

        code = YamlMethod().read_data('code.yaml')['code']

        data = CaseName.query.all()
        case_name_info = []
        max_id = 0
        for i in data:
            case_name_schema = CaseNameSchema()
            case_name_data = case_name_schema.dump(i)
            # 判断是否是最大id
            if case_name_data['id'] > max_id:
                max_id = case_name_data['id']
            # 将单条数据库信息添加到info中
            case_name_info.append(case_name_data)

        # 创建字典以便快速查找
        lookup = {item['id']: {**item, 'children': []} for item in case_name_info}
        # 生成树形结构
        tree = []
        for item in case_name_info:
            if item['parent_id'] == 0:
                tree.append(lookup[item['id']])
            else:
                parent = lookup[item['parent_id']]
                parent['children'].append(lookup[item['id']])
        # 对children进行排序
        for node in tree:
            sort_children(node)

        res = {
            'code': code[0],
            'message': 'success',
            'data': {
                'CaseNameTree': tree,
                'startId': max_id
            }
        }

        return res
